export class AreaCalculator {
  constructor(canvas) {
    this.canvas = canvas
    this.ctx = canvas.getContext('2d')
  }

  // 计算指定颜色的像素数量（面积）
  calculateAreaByColor(color) {
    const target = (color || '').toLowerCase()
    const imageData = this.ctx.getImageData(0, 0, this.canvas.width, this.canvas.height)
    const data = imageData.data
    let count = 0

    for (let i = 0; i < data.length; i += 4) {
      const r = data[i]
      const g = data[i + 1]
      const b = data[i + 2]
      const a = data[i + 3]

      // 跳过透明像素
      if (a === 0) continue

      // 将RGB转换为十六进制颜色进行比较
      const pixelColor = this.rgbToHex(r, g, b)
      if (pixelColor === target) {
        count++
      }
    }

    return count
  }

  // 计算所有颜色的面积
  calculateAllAreas() {
    const imageData = this.ctx.getImageData(0, 0, this.canvas.width, this.canvas.height)
    const data = imageData.data
    const areas = new Map()

    for (let i = 0; i < data.length; i += 4) {
      const r = data[i]
      const g = data[i + 1]
      const b = data[i + 2]
      const a = data[i + 3]

      // 跳过透明像素
      if (a === 0) continue

      const pixelColor = this.rgbToHex(r, g, b)
      areas.set(pixelColor, (areas.get(pixelColor) || 0) + 1)
    }

    return areas
  }

  // 计算指定区域的面积
  calculateAreaInRegion(x, y, width, height, color) {
    const imageData = this.ctx.getImageData(x, y, width, height)
    const data = imageData.data
    let count = 0

    for (let i = 0; i < data.length; i += 4) {
      const r = data[i]
      const g = data[i + 1]
      const b = data[i + 2]
      const a = data[i + 3]

      if (a === 0) continue

      const pixelColor = this.rgbToHex(r, g, b)
      if (pixelColor === color) {
        count++
      }
    }

    return count
  }

  // 获取画布上所有使用的颜色
  getAllColors() {
    const imageData = this.ctx.getImageData(0, 0, this.canvas.width, this.canvas.height)
    const data = imageData.data
    const colors = new Set()

    for (let i = 0; i < data.length; i += 4) {
      const r = data[i]
      const g = data[i + 1]
      const b = data[i + 2]
      const a = data[i + 3]

      if (a > 0) {
        const color = this.rgbToHex(r, g, b)
        colors.add(color)
      }
    }

    return Array.from(colors)
  }

  // 检查指定位置是否已被涂色
  isPositionPainted(x, y) {
    const pixel = this.ctx.getImageData(x, y, 1, 1).data
    return pixel[3] > 0 // alpha通道 > 0 表示有颜色
  }

  // 获取指定位置的颜色
  getColorAtPosition(x, y) {
    const pixel = this.ctx.getImageData(x, y, 1, 1).data
    if (pixel[3] === 0) return null // 透明

    return this.rgbToHex(pixel[0], pixel[1], pixel[2])
  }

  // RGB转十六进制
  rgbToHex(r, g, b) {
    return ('#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)).toLowerCase()
  }

  // 十六进制转RGB
  hexToRgb(hex) {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
    return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16)
    } : null
  }

  // 计算画布总像素数
  getTotalPixels() {
    return this.canvas.width * this.canvas.height
  }

  // 计算画布已涂色像素数
  getPaintedPixels() {
    const imageData = this.ctx.getImageData(0, 0, this.canvas.width, this.canvas.height)
    const data = imageData.data
    let count = 0

    for (let i = 0; i < data.length; i += 4) {
      if (data[i + 3] > 0) { // alpha > 0
        count++
      }
    }

    return count
  }

  // 获取涂色覆盖率
  getPaintCoverage() {
    const total = this.getTotalPixels()
    const painted = this.getPaintedPixels()
    return (painted / total) * 100
  }

  // 更新指定位置的面积（用于实时同步）
  updateArea(x, y, color, brushSize) {
    // 这个方法主要用于实时同步时的面积更新
    // 实际的面积计算仍然通过calculateAreaByColor方法进行
    // 这里可以添加一些缓存或优化逻辑
  }
}
